<template>
  <div class="app-container">
    <section>
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="formInline">
          <el-form-item>
            <el-date-picker
              v-model="formInline.date"
              @change="dateChangebirthday1"
              :picker-options="pickerOptions"
              type="daterange"
              format="yyyy-MM-dd "
              value-format="yyyy-MM-dd "
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="PurchaseGetBranchSalesData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="downloadLoading"
              class="filter-item"
              type="primary"
              icon="document"
              @click="handleDownload"
            >导出</el-button>
          </el-form-item>
        </el-form>
      </el-col>

      <el-table :data="RetailList" border style="width: 100%" v-loading="RetailListLoading">
        <!--show-summary :summary-method="getSummaries"-->
        <el-table-column prop="Ins" label="日期" align="center" :formatter="formatDate"></el-table-column>
        <el-table-column prop="BranchAddress" label="店铺地址" align="center"></el-table-column>
        <el-table-column prop="EmpInfoMobile" label="店铺电话" align="center"></el-table-column>
        <el-table-column prop="TotailAmount" label="销售金额" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.TotailAmount}}元</span>
          </template>
        </el-table-column>

        <!-- <el-table-column label="详情" align="center">
          <template slot-scope="scope">
            <el-button type="primary" @click="handleLook(scope.row)">查看</el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <el-pagination
        background
        layout=" prev, pager, next, jumper"
        @current-change="handleOutCurrentChange"
        :page-size="outpageSize"
        :total="outTotal"
        style="float:right;margin-top: 10px;"
      ></el-pagination>
    </section>
  </div>
</template>

<script>
import {
  GetRetailList,
  PurchaseGetBranchSalesData
} from "../../api/api";
import Config from "../../api/config";

export default {
  data() {
    return {
      downloadLoading: false,
      RetailListLoading: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },

        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "本周",
            onClick(picker) {
              const end = new Date();
              console.log(this);
              console.log(formatDate);
              var now = new Date(); //当前日期
              var nowDayOfWeek = now.getDay(); //今天本周的第几天
              var nowDay = now.getDate(); //当前日
              var nowMonth = now.getMonth(); //当前月
              var nowYear = now.getYear(); //当前年
              nowYear += nowYear < 2000 ? 1900 : 0; //
              var weekStartDate = new Date(
                nowYear,
                nowMonth,
                nowDay - nowDayOfWeek
              );
              const start = weekStartDate;
              start.setTime(start);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "上周",
            onClick(picker) {
              var now = new Date(); //当前日期
              var nowDayOfWeek = now.getDay(); //今天本周的第几天
              var nowDay = now.getDate(); //当前日
              var nowMonth = now.getMonth(); //当前月
              var nowYear = now.getYear(); //当前年
              nowYear += nowYear < 2000 ? 1900 : 0; //
              const start = new Date(
                nowYear,
                nowMonth,
                nowDay - nowDayOfWeek - 7
              );
              start.setTime(start);
              const end = new Date(
                nowYear,
                nowMonth,
                nowDay - nowDayOfWeek - 1
              );
              start.setTime(start);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "本月",
            onClick(picker) {
              var now = new Date(); //当前日期
              var nowDayOfWeek = now.getDay(); //今天本周的第几天
              var nowDay = now.getDate(); //当前日
              var nowMonth = now.getMonth(); //当前月
              var nowYear = now.getYear(); //当前年
              nowYear += nowYear < 2000 ? 1900 : 0; //
              const end = new Date();
              const start = new Date(nowYear, nowMonth, 1);
              start.setTime(start);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "上月",
            onClick(picker) {
              var now = new Date(); //当前日期
              var nowDayOfWeek = now.getDay(); //今天本周的第几天
              var nowDay = now.getDate(); //当前日
              var nowMonth = now.getMonth(); //当前月
              var nowYear = now.getYear(); //当前年
              nowYear += nowYear < 2000 ? 1900 : 0; //
              var lastMonthDate = new Date(); //上月日期
              lastMonthDate.setDate(1);
              lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
              var lastYear = lastMonthDate.getYear();
              var lastMonth = lastMonthDate.getMonth();
              //								const end = new Date();
              const start = new Date(nowYear, nowMonth - 1, 1);
              start.setTime(start);
              const end = new Date(
                nowYear,
                nowMonth - 1,
                getMonthDays(lastMonth)
              );
              start.setTime(start);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "近3天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "近5天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 5);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "近7天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近10天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 10);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),

      BranchName: "",
      lookForm: {},
      lookFormVisible: false,
      formInline: {
        date: [],
        starttime: "",
        endTime: "",
        BranchId: 0
      },
      page: 1,
      pageSize: 50,
      total: 10000000000,
      outpage: 1,
      outpageSize: 50,
      outTotal: 100000000000,
      tableData: [],
      RetailList: [],
      showDate: new Date()
    };
  },
  created() {
    this.PurchaseGetBranchSalesData();
    this.getTime();
  },
  methods: {
    startTimeStatus: function(value) {
      this.formInline.starttime = value;
      let currentTime = new Date(value).getTime();
      let time = currentTime + 3600 * 1000 * 24 * 7;
      console.log(time);
      this.formInline.endtime =
        time > new Date(this.formInline.endtime).getTime()
          ? this.formInline.endtime
          : this.formatDate(time);
      console.log(this.formInline.starttime);
      this.startDatePicker = currentTime => {
        return {
          disabledDate(currentTime) {
            return (
              currentTime <
              new Date(this.formInline.endtime).getTime() - 3600 * 1000 * 24 * 7
            ); //开始时间不选时，结束时间最大值小于等于当天
          }
        };
      };
      console.log(this.startDatePicker);
    },
    // 时间结束选择器
    endTimeStatus: function(value) {
      let currentTime = new Date(value).getTime();
      let starttime = new Date(this.formInline.starttime).getTime();
      this.formInline.starttime =
        currentTime > starttime ? this.formInline.starttime : value;
      console.log(this.formInline.starttime);
    },
    beginDate() {
      let self = this;
      return {
        disabledDate(time) {
          if (self.formInline.endtime) {
            return time.getTime() < new Date(self.formInline.endtime).getTime(); //开始时间不选时，结束时间最大值小于等于当天
          } else {
            // 不能大于当前日期
            return time.getTime() > Date.now();
          }
        }
      };
    },
    //提出结束时间必须大于提出开始时间
    processDate() {
      let self = this;
      return {
        disabledDate(time) {
          if (self.formInline.starttime) {
            return (
              new Date(self.formInline.starttime).getTime() - 8.64e7 >
                time.getTime() ||
              time.getTime() > Date.now() ||
              time.getTime() >
                new Date(self.formInline.starttime).getTime() +
                  3600 * 1000 * 24 * 7
            );
          } else {
            return time.getTime() > Date.now(); //开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    getTime() {
      let date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      let d = date.getDate();
      let dt = date.getDate() - 1;
      let endTime = y + "-" + m + "-" + d;
      let starttime = y + "-" + m + "-" + dt;
      this.formInline.date[0] = starttime;
      this.formInline.date[1] = endTime;
      this.PurchaseGetBranchSalesData();
    },
    formatDate: function(row) {
      var date = new Date(row.Ins);
      var yy = date.getFullYear();
      if (yy < 1900) yy = yy + 1900;
      var MM = date.getMonth() + 1;
      if (MM < 10) MM = "0" + MM;
      var dd = date.getDate();
      if (dd < 10) dd = "0" + dd;
      var hh = date.getHours();
      if (hh < 10) hh = "0" + hh;
      var mm = date.getMinutes();
      if (mm < 10) mm = "0" + mm;
      var ss = date.getSeconds();
      if (ss < 10) ss = "0" + ss;
      return yy + "年" + MM + "月" + dd + "日" + " " + hh + ":" + mm + ":" + ss;
    },
    formatShowDate: function(dt) {
      var date = new Date(dt);
      var yy = date.getFullYear();
      if (yy < 1900) yy = yy + 1900;
      var MM = date.getMonth() + 1;
      if (MM < 10) MM = "0" + MM;
      var dd = date.getDate();
      if (dd < 10) dd = "0" + dd;
      var hh = date.getHours();
      if (hh < 10) hh = "0" + hh;
      var mm = date.getMinutes();
      if (mm < 10) mm = "0" + mm;
      var ss = date.getSeconds();
      if (ss < 10) ss = "0" + ss;
      return yy + "-" + MM + "-" + dd;
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总价";
          return;
        }
        if (index !== 5) {
          return;
        }
        const values = data.map(item => {
          return Number(item[column.property]);
        });
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += "元";
        }
      });

      return sums;
    },
    //获取门店销售数据
    PurchaseGetBranchSalesData() {
      var self = this;
      var para = {
        SessionId: JSON.parse(localStorage.getItem("userinfo")).SessionId,
        Page: this.outpage,
        PageSize: this.outpageSize,
        Start: this.formInline.date[0],
        End: this.formInline.date[1],
        BranchId: this.$route.query.BranchId
      };
      this.RetailListLoading = true;
      console.log(para);
      PurchaseGetBranchSalesData(para).then(res => {
        if (res.data.Status != 1) {
          this.$message({
            message: res.data.Description,
            type: "error"
          });
          return;
        } else {
          var vdata = JSON.parse(Base64.decode(res.data.Data));
          console.log(vdata);
          self.RetailList = vdata.DataList;
          self.outTotal = vdata.TotalCount;
        }
        self.RetailListLoading = false;
      });
    },

    dateChangebirthday1(val) {
      this.startTime = val;
      console.log(this.startTime);
    },

    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = [
          "店铺ID",
          "店铺名称",
          "日期",
          "店铺地址",
          "店铺联系电话",
          "销售数量",
          "销售金额"
        ];
        const filterVal = [
          "BranchId",
          "BranchName",
          "Ins",
          "BranchAddress",
          "BranchMobile",
          "Count",
          "TotailAmount"
        ];
        const data = this.formatJson(filterVal, this.RetailList);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "门店业绩"
        });
        this.downloadLoading = false;
      });
    },

    handleDownload2() {
      this.downLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = [
          "商品ID",
          "商品名称",
          "单位",
          "商品类别",
          "商品条码",
          "折扣",
          "销售数量",
          "单价",
          "会员",
          "操作人"
        ];
        const filterVal = [
          "SKUId",
          "SKUName",
          "UnitNo",
          "SKUClassname",
          "SaleBarcode",
          "Discount",
          "SaleQty",
          "UnitPrice",
          "MemberMobile",
          "EmpInfoMobile"
        ];
        const data = this.formatJson(filterVal, this.tableData);
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: "门店业绩明细"
        });
        this.downLoading = false;
      });
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },

    //查看
    handleLook(row) {
      var BranchId = row.BranchId;
      if (BranchId == 0) {
        this.$message({
          message: "出现异常",
          type: "error"
        });
      }
      this.showDate = row.Ins;
      this.formInline.BranchId = BranchId;
      this.lookFormVisible = true;
      this.GetRetailListAction();
    },
    //关闭查看页面
    handleClose(done) {
      //				this.formInline.BranchId = 0;
      this.lookFormVisible = false;
      //				this.GetRetailListAction();
    },
    //两个翻页
    handleOutCurrentChange(val) {
      this.outpage = val;
      console.log(val, 1);
      this.GetOutRetailList();
    },
    handleCurrentChange(val) {
      this.page = val;
      console.log(val, 1);
      this.GetRetailListAction();
    }
  }
};
</script>

<style>
.el-form-item--medium .el-form-item__content,
.el-form-item--medium .el-form-item__label {
  color: #333333;
}
</style>